const path = require('path');
const bytenode = require('bytenode');
const { run } = require('runjs');
require('console-color-mr');
const fs = require('fs');
var { spawn } = require('child_process');

let tempPath = path.resolve(__dirname, '../jsc');
if (!fs.existsSync(tempPath)) {
  fs.mkdirSync(tempPath);
}

const copyCodeFile = async (src, dst) => {
  const checkDirectory = (src, dst, callback) => {
    fs.access(dst, fs.constants.F_OK, (err) => {
      if (err) {
        fs.mkdirSync(dst);
        callback(src, dst);
      } else {
        callback(src, dst);
      }
    });
  };
  let paths = fs.readdirSync(src);
  paths = paths.filter(
    (item) =>
      item != 'node_modules' &&
      item != 'package-lock.json' &&
      item != 'jsc.js' &&
      item != '.DS_Store' &&
      item != 'online' &&
      item != 'home' &&
      item != 'book'
  );
  paths.forEach((item) => {
    let _src = path.resolve(src, item);
    let _dst = path.resolve(dst, item);
    fs.stat(_src, (err, stats) => {
      if (err) throw err;
      if (stats.isFile()) {
        if (/.js$/.test(_src) && !/main.js$/.test(_src)) {
          run(`javascript-obfuscator ${_src} --output ${_dst}`);
          bytenode.compileFile(_dst, _dst + 'c');
          console.log(`convert ${_src} to jsc`.blue);
          fs.unlinkSync(_dst);
        } else {
          let readable = fs.createReadStream(_src);
          let writable = fs.createWriteStream(_dst);
          readable.pipe(writable);
        }
      } else if (stats.isDirectory()) {
        checkDirectory(_src, _dst, copyCodeFile);
      }
    });
  });
};

const deleteFolder = (res) => {
  var files = [];
  if (fs.existsSync(res) && !/node_modules$/.test(res) && !/www$/.test(res)) {
    files = fs.readdirSync(res);
    files.forEach((file) => {
      var curPath = path.resolve(res, file);
      if (fs.statSync(curPath).isDirectory()) {
        deleteFolder(curPath);
      } else {
        fs.unlinkSync(curPath);
      }
    });
    if (!/jsc$/.test(res)) {
      fs.rmdirSync(res);
    }
  }
};

(async () => {
  spawn('rm', ['-rf', './jsc/www']);
  deleteFolder(path.resolve(__dirname, '../jsc'));
  spawn('cp', ['-r', './app/www', './jsc']);
  spawn('cp', ['-r', './app/node_modules', './jsc']);
  let src = __dirname;
  let des = path.resolve(__dirname, '../jsc');
  copyCodeFile(src, des);
})();
